﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using System.Text;
using System.Xml.XPath;

namespace TKWeb.Tool
{
	public partial class XPath : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected void btnRun_Click(object sender, EventArgs e)
		{
			try
			{
				string oldValue = null;
				string value = string.Empty;
				StringBuilder sb = new StringBuilder();
				XmlDocument doc = FromHtml(tbSource.Text.Trim());

				XPathNavigator nav = doc.CreateNavigator();
				XPathNodeIterator nodes = nav.Select(tbXPath.Text.Trim());
				while (nodes.MoveNext())
				{
					oldValue = nodes.Current.Value.Trim().Replace("\t", "").Replace("\n", "").Replace("\r", "");
					if (nodes.Current.Name.ToLower() == "img")
					{
						oldValue = nodes.Current.GetAttribute("src", string.Empty);
					}


					XPathNodeIterator childNodes = nodes.Current.Select("./*");
					while (childNodes.MoveNext())
					{
						childNodes.Current.DeleteSelf();
					}

					value = nodes.Current.Value.Trim().Replace("\t", "").Replace("\n", "").Replace("\r", "");
					if (string.IsNullOrEmpty(value))
					{
						value = oldValue;
					}

					sb.Append(value);
					sb.AppendLine();
				}
				tbResult.Text = sb.ToString();
			}
			catch
			{
			}
		}

		private XmlDocument FromHtml(string html)
		{
			html = html.Replace("xmlns=\"http://www.w3.org/1999/xhtml\"", "");
			// setup SGMLReader
			Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader();
			sgmlReader.DocType = "HTML";
			sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
			sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
			sgmlReader.InputStream = new StringReader(html);

			// create document
			XmlDocument doc = new XmlDocument();
			doc.PreserveWhitespace = true;
			doc.XmlResolver = null;
			doc.Load(sgmlReader);
			return doc;
		}
	}
}